package com.example.shirotest.study;

public class ArrBinaryTreeTest {

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7};

        ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);
        //1-前序
        //arrBinaryTree.preOrder();
        //2-中序
        //arrBinaryTree.infixOrder();
        //3-后序
        arrBinaryTree.postOrder();

    }

}


class ArrBinaryTree{
    private int[] arr; //存储数据节点的数组

    public ArrBinaryTree(int[] arr){
        this.arr = arr;
    }

    public void preOrder(){
        this.preOrder(0);
    }

    //前序遍历
    public void preOrder(int index){
        if(arr == null || arr.length == 0){
            System.out.println("Array is empty");
            return;
        }
        //输出当前这个元素
        System.out.println(arr[index]);
        //向左递归遍历
        if((index*2 +1) < arr.length){
            preOrder(2*index+1);
        }
        //向右递归遍历
        if((index*2 + 2) < arr.length){
            preOrder(2*index +2);
        }
    }

    public void infixOrder(){
        this.infixOrder(0);
    }

    //前序遍历
    public void infixOrder(int index){
        if(arr == null || arr.length == 0){
            System.out.println("Array is empty");
            return;
        }
        //向左递归遍历
        if((index*2 +1) < arr.length){
            infixOrder(2*index+1);
        }
        //输出当前这个元素
        System.out.println(arr[index]);
        //向右递归遍历
        if((index*2 + 2) < arr.length){
            infixOrder(2*index +2);
        }
    }

    public void postOrder(){
        this.postOrder(0);
    }

    //后序遍历
    public void postOrder(int index){
        if(arr == null || arr.length == 0){
            System.out.println("Array is empty");
            return;
        }
        //向左递归遍历
        if((index*2 +1) < arr.length){
            postOrder(2*index+1);
        }
        //向右递归遍历
        if((index*2 + 2) < arr.length){
            postOrder(2*index +2);
        }
        //输出当前这个元素
        System.out.println(arr[index]);
    }


}

